from typing import List
from .model import UserTemplate
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    template_id: str = Field(None, alias='template_id')    
    user_id: str = Field(None, alias='user_id')


# 设置请求接收字段
class UserTemplateSchemaIn(ModelSchema):

    class Config:
        model = UserTemplate
        model_exclude = ['creation_on', 'change_on',  'change_by', 'creation_by', 'id']


# 设置响应字段
class UserTemplateSchemaOut(ModelSchema):

    class Config:
        model = UserTemplate
        model_fields = '__all__'


# 创建UserTemplate
@router.post('/user_template', response=UserTemplateSchemaOut)
def create_user_template(request, data: UserTemplateSchemaIn):
    user_template = create(request, data, UserTemplate)
    return user_template


# 删除UserTemplate
@router.delete('/user_template/{id}')
def delete_user_template(request, id: int):
    delete(id, UserTemplate)
    return {'success': True}


# 更新UserTemplate
@router.put('/user_template/{id}', response=UserTemplateSchemaOut)
def update_user_template(request, id: int, data: UserTemplateSchemaIn):
    user_template = update(request, id, data, UserTemplate)
    return user_template


# 获取UserTemplate
@router.get('/user_template', response=List[UserTemplateSchemaOut])
@paginate(MyPagination)
def list_user_template(request, filters: Filters = Query(...)):
    qs = retrieve(request, UserTemplate, filters)
    return qs


# 导入
@router.get('/user_template/all/export')
def export_user_template(request):
    export_fields = ('template_id', 'user_id', )
    return export_data(request, UserTemplate, UserTemplateSchemaOut, export_fields)


# 导出
@router.post('/user_template/all/import')
def import_user_template(request, data: ImportSchema):
    import_fields = ('template_id', 'user_id', )
    return import_data(request, UserTemplate, UserTemplateSchemaIn, data, import_fields)
    